#include "Ringqueue.hpp"
#include <string>
#include <pthread.h>
#include <unistd.h>

extern int data = 1;
pthread_mutex_t data_mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t cum_mutex = PTHREAD_MUTEX_INITIALIZER;

struct Thread
{
    Ringqueue<int> *rq;
    string name;
};

void* Comsumer(void* argv)
{
    Thread *td = static_cast<Thread*>(argv);
    while(true)
    {
        pthread_mutex_lock(&cum_mutex);
        sleep(3);
        int t;
        t = td->rq->Pop();
        cout << td->name << ":消费者拿到了一个数据->" << t << endl;
        pthread_mutex_unlock(&cum_mutex);
    }
}

void* Productor(void* argv)
{
    Thread *td = static_cast<Thread*>(argv);
    while(true)
    {
        pthread_mutex_lock(&data_mutex);
        sleep(1);
        cout << td->name << ":生产了一个任务->" << data << endl;

        td->rq->Enqueue(data);

        data++;
        pthread_mutex_unlock(&data_mutex);
    }
}

int main()
{
    Ringqueue<int> *rq = new Ringqueue<int>();
    pthread_t p[2],c[3];

    Thread *td1 = new Thread();
    td1->name = "Thread-1p";
    td1->rq = rq;
    pthread_create(&p[0],nullptr,Productor,td1);

    Thread *td2 = new Thread();
    td2->name = "Thread-2p";
    td2->rq = rq;
    pthread_create(&p[1],nullptr,Productor,td2);

    Thread *td3 = new Thread();
    td3->name = "Thread-3c";
    td3->rq = rq;
    pthread_create(&c[0],nullptr,Comsumer,td3);

    Thread *td4 = new Thread();
    td4->name = "Thread-4c";
    td4->rq = rq;
    pthread_create(&c[1],nullptr,Comsumer,td4);

    Thread *td5 = new Thread();
    td5->name = "Thread-5c";
    td5->rq = rq;
    pthread_create(&c[2],nullptr,Comsumer,td5);

    pthread_join(p[0], nullptr);
    pthread_join(p[1], nullptr);
    pthread_join(c[0], nullptr);
    pthread_join(c[1], nullptr);
    pthread_join(c[2], nullptr);

    return 0;
}